package com.cheer.job;

import com.cheer.entity.MallOrderEntity;
import com.cheer.entity.MallOrderFinishEntity;
import com.cheer.enums.MallOrderStatusEnum;
import com.cheer.enums.MallRefundStatusEnum;
import com.cheer.service.MallOrderFinishService;
import com.cheer.service.MallOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 自动确认收货定时任务
 *
 * @author cheer
 */
@Component
@Slf4j
public class OrderAutoFinishJob {

    @Autowired
    private MallOrderFinishService mallOrderFinishService;

    @Autowired
    private MallOrderService mallOrderService;

    @Scheduled(cron = "0 */10 * * * ?")
    public void containerDelete() {
        try {
            // 查询到时自动确认的订单
            List<MallOrderFinishEntity> toFinishOrder = mallOrderFinishService.listToFinishOrder();

            // 处理自动确认的订单
            for (MallOrderFinishEntity orderFinish : toFinishOrder) {
                try {
                    MallOrderEntity order = mallOrderService.getById(orderFinish.getOrderId());
                    if (order != null && Objects.equals(order.getStatus(), MallOrderStatusEnum.DELIVERED.getCode())) {
                        if (Objects.equals(order.getRefundStatus(), MallRefundStatusEnum.TO_REFUND.getCode())){
                            continue;
                        }

                        MallOrderEntity updateOrder = new MallOrderEntity()
                                .setId(order.getId())
                                .setStatus(MallOrderStatusEnum.FINISHED.getCode());
                        mallOrderService.updateById(updateOrder);

                        mallOrderFinishService.removeById(orderFinish.getId());
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
